import json

import pyperclip
import time
import requests
import socket
import fcntl
import struct


class jianting():
    lastCopyTime = 0.0
    initData = pyperclip.paste()
    host = "http://xxxxxxxx:port"
    store = "123"
    timeout = 100

    def clipboard_get(self):
        thisCopyData = pyperclip.paste()
        return thisCopyData

    def clipboard_copy(self, content, serverTime):
        pyperclip.copy(content)
        self.lastCopyTime = serverTime
        self.initData = content

    def getByServer(self):
        try:
            response = requests.request("GET", self.host + "/xxs/cp/g?store=" + self.store, timeout=self.timeout)
            if response.status_code == 200:
                content = json.loads(response.text)
                return content
            else:
                return None
        except Exception:
            print('/xxs/cp/g error')

    def saveToServer(self, content):
        dataStr = json.dumps({'store': self.store, 'content': content})
        headers = {
            'Content-Type': 'application/json'
        }
        try:
            response = requests.request("POST", self.host + '/xxs/cp/s', headers=headers, data=dataStr,
                                        timeout=self.timeout)
            print('up data' + content + ',result:' + response.text)
        except Exception:
            print('/xxs/cp/s error')

    def main(self):
        while True:
            txt = self.clipboard_get()
            if txt != self.initData and txt != '':
                self.initData = txt  # 没查到要替换的子串，返回None
                self.saveToServer(txt)

            content = self.getByServer()
            if content is not None and content['content'] is not None:
                serverContent = content['content']
                serverTime = content['time']
                if serverTime > self.lastCopyTime:
                    self.clipboard_copy(serverContent, serverTime)
            time.sleep(0.1)


if __name__ == '__main__':
    jianting().main()